package com.fanfanwang.ffw.app.ui.my;

import java.lang.reflect.Type;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import com.fanfanwang.ffw.app.AppConstant;
import com.fanfanwang.ffw.app.AppManager;
import com.fanfanwang.ffw.app.R;
import com.fanfanwang.ffw.app.asynctask.IsregAsyncTask;
import com.fanfanwang.ffw.app.asynctask.RegAsyncTask;
import com.fanfanwang.ffw.app.asynctask.UpdateMobileAsyncTask;
import com.fanfanwang.ffw.app.base.BaseActivity;
import com.fanfanwang.ffw.app.bean.IsRegBean;
import com.fanfanwang.ffw.app.bean.SmsBean;
import com.fanfanwang.ffw.app.common.LogUtil;
import com.fanfanwang.ffw.app.common.ToastAlone;
import com.fanfanwang.ffw.app.tools.MyTextUtils;
import com.fanfanwang.ffw.app.tools.SharedPreferencesUtil;
import com.fanfanwang.ffw.app.ui.login.LoginAct;
import com.fanfanwang.ffw.app.ui.login.RegisterAct.MyCount;
import com.fanfanwang.ffw.app.widget.CommonTitleBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**
 * 修改绑定的手机号
 * 
 * @author Administrator
 * 
 */
public class MyUpdateBoundTelAct extends BaseActivity {

	private CommonTitleBar commonTitleBar;
	private Activity mAct;
	private Intent mIntent;
	private TextView now_mobile;
	private EditText et_new_mobile, et_yzm;
	public Button re_bt_getcode;
	private Button confirm_btn_complete;

	public static IIsRegable iIsRegable;
	public static IUpdateMobileable iUpdateMobileable;
	public StringBuffer smsString = new StringBuffer();// 这个是判断这个手机号是合法的，可以注册，然后返回的验证码
	private String newMobile="";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		AppManager.getAppManager().addActivity(this);
		initView();
		initSMSsdk();
		initData();
		setListener();
	}

	public void initSMSsdk() {
		SMSSDK.initSDK(this, AppConstant.APPKEY, AppConstant.APPSECRET);
		EventHandler eh = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {

				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				handler.sendMessage(msg);
			}

		};
		SMSSDK.registerEventHandler(eh);
	}
	@Override
	public void initView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_my_bound_tel);
		mAct = this;
		commonTitleBar = (CommonTitleBar) findViewById(R.id.common_titlebar);
		now_mobile = (TextView) findViewById(R.id.now_mobile);
		et_new_mobile = (EditText) findViewById(R.id.et_new_mobile);
		et_yzm = (EditText) findViewById(R.id.et_yzm);
		re_bt_getcode = (Button) findViewById(R.id.re_bt_getcode);
		confirm_btn_complete = (Button) findViewById(R.id.confirm_btn_complete);
	}

	@Override
	public void setListener() {
		commonTitleBar.setToolBarReturnOnclickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		re_bt_getcode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				newMobile = et_new_mobile.getText().toString();
				if (!TextUtils.isEmpty(newMobile)&&MyTextUtils.isMobileNO(newMobile)) {
					new IsregAsyncTask(mAct, newMobile).execute("");
				} else {
					ToastAlone.showToast(mAct, getString(R.string.mobile_error), Toast.LENGTH_SHORT)
					.show();
				}

			}
		});
		confirm_btn_complete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String yzm=et_yzm.getText().toString();
				if (!TextUtils.isEmpty(yzm)) {
					// 验证一下验证码。如果成功就会回调
					SMSSDK.submitVerificationCode("86", newMobile, yzm);
					//					new UpdateMobileAsyncTask(mAct, SharedPreferencesUtil
					//							.getInstance(mAct).getUserId(), et_new_mobile
					//							.getText().toString()).execute("");
				} else {
					ToastAlone.showToast(mAct,  getString(R.string.yzm_failed),
							Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	public class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			re_bt_getcode.setText(getString(R.string.register_reget));
			re_bt_getcode.setClickable(true);
			re_bt_getcode.setBackgroundResource(R.drawable.btn_selector);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			re_bt_getcode.setText("(" + millisUntilFinished / 1000 + ")");
			re_bt_getcode.setClickable(false);
			re_bt_getcode.setBackgroundResource(R.drawable.btn_back_3);// 灰色
		}

	}

	@Override
	public void initData() {
		// TODO Auto-generated method stub
		commonTitleBar.setCenterText(getString(R.string.update_bound_tel));
		commonTitleBar.setReturnVisible();
		if (!TextUtils.isEmpty(SharedPreferencesUtil.getInstance(mAct)
				.getUsername())) {
			now_mobile.setText(SharedPreferencesUtil.getInstance(mAct)
					.getUsername());
		}
		setInterface();
	}

	public void setInterface() {
		iIsRegable = new IIsRegable() {

			@Override
			public void SetIsRegSms(IsRegBean data) {
				// TODO Auto-generated method stub
				//				smsString.append(data.sms);
				//				LogUtil.e("------MyUpdateBoundTel SMS", smsString.toString());
				//				new MyCount(60000, 1000).start();
				SMSSDK.getVerificationCode("86", newMobile);
			}

			@Override
			public void setIsRegSmsFailed() {
				// TODO Auto-generated method stub
//				new MyCount(60000, 1000).start();
			}
		};
		iUpdateMobileable=new IUpdateMobileable() {

			@Override
			public void setUpdateMobileSuccess() {
				// TODO Auto-generated method stub
				ToastAlone.showToast(mAct, getString(R.string.update_then_login)).show();
				SharedPreferencesUtil.getInstance(mAct).putUserId(null);
				SharedPreferencesUtil.getInstance(mAct).putUsername(null);
				SharedPreferencesUtil.getInstance(mAct).putTruename(null);
				SharedPreferencesUtil.getInstance(mAct).putCarnumber(null);
				AppManager.getAppManager().finishAllActivity();
				AppConstant.user_id = "";
				AppConstant.username = "";
				Intent mIntent = new Intent(mAct,
						LoginAct.class);
				mIntent.putExtra("isNeedIntent", true);
				startActivity(mIntent);
				finish();
			}
		};
	}

	public interface IIsRegable {
		public void SetIsRegSms(IsRegBean data);
		public void setIsRegSmsFailed();
	}

	public interface IUpdateMobileable {
		public void setUpdateMobileSuccess();
	}
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int event = msg.arg1;
			int result = msg.arg2;
			Object data = msg.obj;
			Log.e("event", "event=" + event);
			if (result == SMSSDK.RESULT_COMPLETE) {
				// 短信注册成功后，返回MainActivity,然后提示新好友
				if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
					// ToastAlone.makeText(getApplicationContext(), "提交验证码成功",
					// 注册，注册成功之后，就跳到主界面
					new UpdateMobileAsyncTask(mAct, SharedPreferencesUtil
							.getInstance(mAct).getUserId(), et_new_mobile
							.getText().toString()).execute("");
				} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
					// 获取验证码成功(1步)
					Toast.makeText(getApplicationContext(), "验证码已经发送,60s后可以重新获取",
							Toast.LENGTH_SHORT).show();
					new MyCount(60000, 1000).start();
				} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {// 返回支持发送验证码的国家列表
					Toast.makeText(getApplicationContext(), "获取国家列表成功",
							Toast.LENGTH_SHORT).show();

				}
			} else {
				((Throwable) data).printStackTrace();
				if(data!=null)
				{
					String json=((Throwable)data).getMessage();

					Type type = new TypeToken<SmsBean>() {
					}.getType();
					SmsBean bean = new SmsBean();
					try {
						bean = new Gson().fromJson(json, type);
						if(!TextUtils.isEmpty(bean.status)&&bean.status.equals("520"))
						{
							ToastAlone.showToast(mAct, "验证码错误");
						}
					} catch (JsonSyntaxException e) {
						e.printStackTrace();
					}
				}
			}

		}

	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SMSSDK.unregisterAllEventHandler();
	}
}
